package org.dubnation.org.service.impl;

import org.dubnation.base.service.impl.BaseServiceImpl;
import org.dubnation.org.domain.Department;
import org.dubnation.org.mapper.DepartmentMapper;
import org.dubnation.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void insert(Department department) {
        departmentMapper.insert(department);
        //如果是一级部门，它的path是本身的id
        //如果是二级部门或三级部门，它的path是上级部门path+自己的id
        if (Objects.isNull(department.getParent().getId())){
            //没有上级
            department.setPath("/" + department.getId()); //获取新增数据的id是依赖sql的获取主键
        }else {
            //有上级
            Department parent = departmentMapper.queryById(department.getParent().getId());
            department.setPath(parent.getPath() + "/" + department.getId());
        }
        departmentMapper.update(department); //新增的时候已经获取主键了，因此可以更新该部门
    }

    @Transactional
    @Override
    public void update(Department department) {
        departmentMapper.update(department);
        if (Objects.isNull(department.getParent().getId())){
            //没有上级
            department.setPath("/" + department.getId());
        }else {
            //有上级
            Department parent = departmentMapper.queryById(department.getParent().getId());
            department.setPath(parent.getPath() + "/" + department.getId());
        }
        departmentMapper.update(department);
    }

    @Override
    public List<Department> getParents() {
        return departmentMapper.getParents();
    }

}
